
"""
    组织
"""

from rest_framework import serializers
from users.models import Organization


class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    label = serializers.CharField(max_length=20, source='name')


class OrganizationUserTreeSerializer(serializers.ModelSerializer):
    """
    组织架构关联角色目录树
    """
    label = serializers.StringRelatedField(source='name')
    children = UserSerializer(many=True, read_only=True, source='userprofilemodel_set')

    class Meta:
        model = Organization
        fields = ('id', 'label', 'pid', 'children')


class OrganizationModelSerializer(serializers.ModelSerializer):
    """
    组织架构列表序列化
    """

    class Meta:
        model = Organization
        fields = ('id', 'name', 'type', 'pid')


class OrganizationModelRetrieveSerializer(serializers.ModelSerializer):
    """
    菜单详情序列化
    """

    class Meta:
        model = Organization
        fields = ('id', 'name', 'type', 'pid')

    def to_representation(self, instance):
        """
        修改序列化前的数据格式
        :param instance:
        :return:
        """
        data = super().to_representation(instance)
        # pid 父级菜单(限制5层)
        if data['id']:
            mid = Organization.objects.filter(id=data['id']).first()
            if mid.pid:
                data['pid'] = [mid.pid.id]
                if mid.pid.pid:
                    data['pid'] = [mid.pid.pid.id, mid.pid.id]
                    if mid.pid.pid.pid:
                        data['pid'] = [mid.pid.pid.pid.id, mid.pid.pid.id, mid.pid.id]
                        if mid.pid.pid.pid.pid:
                            data['pid'] = [mid.pid.pid.pid.pid.id, mid.pid.pid.pid.id, mid.pid.pid.id, mid.pid.id]
                            if mid.pid.pid.pid.pid.pid:
                                data['pid'] = [mid.pid.pid.pid.pid.pid.id, mid.pid.pid.pid.pid.id, mid.pid.pid.pid.id,
                                               mid.pid.pid.id, mid.pid.id]
                                if mid.pid.pid.pid.pid.pid.pid:
                                    data['pid'] = [mid.pid.pid.pid.pid.pid.pid.id, mid.pid.pid.pid.pid.pid.id,
                                                   mid.pid.pid.pid.pid.id, mid.pid.pid.pid.id, mid.pid.pid.id,
                                                   mid.pid.id]
        return data
